package com.sanpu.kxe.jump.jsbridge;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.OnItemClickListener;
import com.sanpu.kxe.R;
import com.sanpu.kxe.business.main.adapter.ShareAdapter;
import com.sanpu.kxe.business.main.bean.UserCenterOutput;
import com.sanpu.kxe.common.cache.CacheManage;
import com.sanpu.kxe.common.cache.CacheModel;
import com.sanpu.kxe.common.interfaces.UrlConstants;
import com.sanpu.kxe.common.utils.CommonUtils;
import com.sanpu.kxe.jump.jsbridge.module.JBArray;
import com.sanpu.kxe.jump.jsbridge.module.JBCallback;
import com.sanpu.kxe.jump.jsbridge.module.JBMap;
import com.sanpu.kxe.jump.jsbridge.module.JSBridgeMethod;
import com.sanpu.kxe.jump.jsbridge.module.JsModule;
import com.sanpu.kxe.jump.jsbridge.module.WritableJBArray;
import com.sanpu.kxe.jump.jsbridge.module.WritableJBMap;
import com.sanpu.kxe.jump.shareutil.ShareUtil;
import com.sanpu.kxe.jump.shareutil.share.ShareListener;
import com.sanpu.kxe.jump.shareutil.share.SharePlatform;
import com.sanpu.kxe.utils.ToastUtil;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import rx.subscriptions.CompositeSubscription;

/**
 * Description：分享
 * Created by 薛勇军 on 2018/6/11.
 */
public class ShareAppModule extends JsModule {

    @Override
    public String getModuleName() {
        return "share";
    }

    private ShareAdapter mShareAdapter;
    private String mShareUrl;
    public CompositeSubscription mSubscription;

    @JSBridgeMethod(methodName = "shareApp")
    public void share(String msg, final JBCallback success, final JBCallback failure) {
        try {
            mShareUrl = UrlConstants.INVITE_REG;
            UserCenterOutput retDatBean = CacheManage.getInstance().getCache(CacheModel.USER_CENTER_KEY);
            if (retDatBean != null) {
                String name = retDatBean.getUserName();
                if (!TextUtils.isEmpty(name)) {
                    mShareUrl += name;
                }
            }
            mShareAdapter = new ShareAdapter(mContext, true);
            DialogPlus dialog = DialogPlus.newDialog(getContext())
                    .setAdapter(mShareAdapter)
                    .setHeader(R.layout.view_dialogplus_header)
                    .setOnItemClickListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(DialogPlus dialog, Object item, View view, int position) {
                            if (position < 0) return;
                            prepareMedia(mShareAdapter.getItem(position).getPlatform());
                        }
                    })
                    .setExpanded(false)  // This will enable the expand feature, (similar to android L share dialog)
                    .create();
            dialog.show();
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtil.showTextViewPromptLong("分享失败");
        }
    }

    private void prepareMedia(final @SharePlatform.Platform int module) {
        if (TextUtils.isEmpty(mShareUrl)) return;
        ShareListener shareListener = new ShareListener() {
            @Override
            public void shareSuccess() {
            }

            @Override
            public void shareFailure(Exception e) {
                ToastUtil.showTextViewPromptLong(e.getMessage());
            }

            @Override
            public void shareCancel() {
            }
        };
        try {
            Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.ic_logo);
            String shareIcon = CommonUtils.getShareIcon();
            String[] shareSummary = CommonUtils.getShareSummary(mContext);
            if (!TextUtils.isEmpty(shareIcon)) {
                ShareUtil.shareMedia(mContext, module, shareSummary[0], shareSummary[1],
                        mShareUrl, shareIcon, shareListener);
            } else {
                ShareUtil.shareMedia(mContext, module, shareSummary[0], shareSummary[1],
                        mShareUrl, bitmap, shareListener);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private void closeSubscription() {
        if (mSubscription != null && !mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
            mSubscription = null;
        }
    }

    @JSBridgeMethod
    public void ajax(JBMap dataMap) {
        final String type = dataMap.getString("type");
        final String url = dataMap.getString("url");
        JBMap data = dataMap.getJBMap("data");
        final StringBuilder params = new StringBuilder();
        for (String key : data.keySet()) {
            params.append(key + "=" + data.get(key) + "&");
        }
        final JBCallback successCallback = dataMap.getCallback("success");
        final JBCallback errorCallback = dataMap.getCallback("error");
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
                    conn.setRequestMethod(type);
                    conn.setDoOutput(true);
                    DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
                    dos.writeBytes(params.toString());
                    dos.flush();
                    dos.close();
                    int resultCode = conn.getResponseCode();
                    if (HttpURLConnection.HTTP_OK == resultCode) {
                        StringBuffer sb = new StringBuffer();
                        String readLine;
                        BufferedReader responseReader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
                        while ((readLine = responseReader.readLine()) != null) {
                            sb.append(readLine).append("\n");
                        }
                        responseReader.close();
                        successCallback.apply(sb.toString());
                    } else {
                        errorCallback.apply("server response error:" + resultCode);
                    }
                } catch (IOException e) {
                    errorCallback.apply(e.getMessage());
                }
            }
        }).start();
    }

    @JSBridgeMethod
    public void test(JBArray array) {
        for (int i = 0; i < array.size(); i++) {
            String output = "" + array.get(i);
            if (array.get(i) != null) {
                output += "##" + array.get(i).getClass();
            }
            Log.d(JsBridge.TAG, output);
        }
        array.getCallback(4).apply("xxx");
        Log.d(JsBridge.TAG, "ret=" + array.getMap(5).getInt("a"));
        array.getMap(5).getCallback("b").apply();
    }

    @JSBridgeMethod
    public void testReturn(JBCallback callback) {
        WritableJBArray jbArray = WritableJBArray.create();
        jbArray.pushInt(1);
        jbArray.pushInt(2);
        jbArray.pushInt(3);
        WritableJBMap jbMap = WritableJBMap.create();
        jbMap.putString("a", "hello");
        jbMap.putString("b", "world");
        callback.apply(jbArray, jbMap);
        Log.d(JsBridge.TAG, jbMap.toString() + "\n" + jbArray.toString());
        Log.d(JsBridge.TAG, getContext() + "#" + getWebViewObject());
    }
}
